'''
NBUitl - Nokia backup file utilities
Copyright (C) 2010 Xiong Huang

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Project homepage: http://code.google.com/p/nbutil/

@author: Xiong Huang, xiong@moblet.cn

Created on Mar 31, 2010

'''
import re

from nbutil.contact import Contact
from nbutil.quotedtext import QuotedText

class NbuFile:
    '''
    Nokia backup file (NBU) parser
    '''
    def __init__(self, filename):
        '''
        Create a NbuFile instance with the given filename
        '''
        self.filename = filename
        self.contacts = None

    def getContacts(self):
        '''
        Get all contacts from this nbu file
        '''
        if self.contacts == None:
            self.contacts = []
            nbuFile = open(self.filename, mode='rb')
            line = nbuFile.readline()
            begin = False
            contact = None
            while line != b'':
                if line.find(b'BEGIN:VCARD') != -1:
                    if contact != None:
                        self.contacts.append(contact)
                    contact = Contact()
                    begin = True
                elif (line.find(b'END:VCARD') != -1):
                    begin = False
                elif begin == True:
                    (key, value) = self.__parse(line.decode())
                    old = contact.get(key)
                    if old != None:
                        if type(old) == list:
                            contact[key] = old.append(value)
                        else:
                            contact[key] = [old, value]
                    else:
                        contact[key] = value
                line = nbuFile.readline()
            nbuFile.close()
        return self.contacts
    
    def __parse(self, text):
        '''
        Parse vcard line
        '''
        (key, value) = text.split(':')
        if key.find('QUOTED-PRINTABLE') != -1:
            encoding = 'UTF-8'
            m = re.search('CHARSET=([^;:]+)', key)
            if m != None:
                encoding = m.groups()[0]
            return (key.split(';')[0], QuotedText.decode(value[:-2].encode(), encoding))
        else:
            return (text[:-2].split(':'))
